<?php
/**
 * 发送手机短信
 * @author yanghj 2014.5.16
 */
class Send_mobileApp extends FrontendApp
{
    var $_user_id;
    var $_mobile_log_mod;
    var $_user_safety_mod;
    var $_member_from;

    function __construct()
    {
        $this->Send_mobileApp();
    }

    function Send_mobileApp()
    {
        parent::FrontendApp();
        $this->_user_id = intval($this->visitor->get('user_id'));
        $this->_member_from = isset($_GET['from']) ? trim($_GET['from']) : 'buyer';
        $this->_mobile_log_mod = &m('mobilelog');
        $this->_user_safety_mod = &m('usersafety');
    }

    function index()
    {
        header("Location:index.php");
    }  

    /**
     * 设置绑定手机
     *
     */
    function set_binding_mobile()
    {
        if (empty($this->_user_id)) {
            $ret_url = urlencode(get_page_url());
            $this->show_warning("please_login", 'login',
                'index.php?app=member&act=login&ret_url=' . $ret_url);
            return;
        }
        $mobile = trim($_POST['phone_mob']);
        $mobile_code = trim($_POST['mobile_verification_code']);
        $binding_mobile = $this->_user_safety_mod->getOne("SELECT binding_mobile FROM {$this->_user_safety_mod->table} WHERE user_id = {$this->_user_id} ");
        if (empty($mobile) || !is_mobile($mobile)) {
            $this->show_warning("手机号码不正确");
            return;
        }
        if($binding_mobile)
        {
            $this->show_warning("你已经绑定手机号码了,不能重复绑定!");
            return;
        }
        if(!isset($_SESSION['start_sent_time']) || time() - $_SESSION['start_sent_time'] > 1800)
        {
            $this->show_warning("手机验证码已无效请重新发送!");
            return;
        }
        if ($mobile != $_SESSION['mobile'])
        {
            $this->show_warning("手机号码不正确!");
            return false;
        }
        if($mobile_code != $_SESSION['mobile_code'])
        {
            $this->show_warning("手机验证码错误!");
            return;
        }
        
        $data = array(
            'user_id' => $this->_user_id,
            'binding_mobile' => $mobile,
            );
        $this->_user_safety_mod->add_edit($data, $this->_user_id);
        if ($this->_user_safety_mod->has_error()) {
            $this->show_warning($this->_user_safety_mod->get_error());

            return;
        }
        
        $this->drop_mobile_session();
        header("Location:index.php?app=account_security&act=authen_verify&mode=set_mobile&step=2&from=" . $this->_member_from);
        return;
        

    }
    
    /**
     * 修改绑定手机
     *
     */
    function edit_binding_mobile()
    {
        if (empty($this->_user_id)) {
            $ret_url = urlencode(get_page_url());
            $this->show_warning("please_login", 'login',
                'index.php?app=member&act=login&ret_url=' . $ret_url);
            return;
        }
        $mobile = trim($_POST['phone_mob']);
        $old_phone_mob = trim($_POST['old_phone_mob']); 
        $mobile_code = trim($_POST['mobile_verification_code']);
        $binding_mobile = $this->_user_safety_mod->getOne("SELECT binding_mobile FROM {$this->_user_safety_mod->table} WHERE user_id = {$this->_user_id} ");
        if (empty($old_phone_mob) || !is_mobile($old_phone_mob) || $old_phone_mob != $binding_mobile ) {
            $this->show_warning("旧手机号码不正确");
            return;
        }
        if (empty($mobile) || !is_mobile($mobile)) {
            $this->show_warning("新手机号码不正确");
            return;
        }
        if(!isset($_SESSION['start_sent_time']) || time() - $_SESSION['start_sent_time'] > 1800)
        {
            $this->show_warning("手机验证码已无效请重新发送!");
            return;
        }
        if ($mobile != $_SESSION['mobile'])
        {
            $this->show_warning("手机号码不正确!");
            return false;
        }
        if($mobile_code != $_SESSION['mobile_code'])
        {
            $this->show_warning("手机验证码错误!");
            return;
        }
        
        $data = array(
            'user_id' => $this->_user_id,
            'binding_mobile' => $mobile,
            );
        $this->_user_safety_mod->add_edit($data, $this->_user_id);
        if ($this->_user_safety_mod->has_error()) {
            $this->show_warning($this->_user_safety_mod->get_error());

            return;
        }
        
        $this->drop_mobile_session();
        header("Location:index.php?app=account_security&act=authen_verify&mode=set_mobile&step=2&from=" . $this->_member_from);
        return;
        

    }

    /**
     * 用AJAX发送手机验证码
     *
     */
    function ajax_send_mobile()
    {

        $mobile = trim($_POST['mobile']);
        $method = trim($_POST['method']);
        //$mobile = '13570489252';
        //$method = 'edit_binging_email';
        $ms = array('statu' => false, 'msg' => '');
        if (empty($method)) {
            $this->show_warning("request_error", 'back_index', 'index.php');
            return;                      
        }
        if (empty($mobile) || !is_mobile($mobile)) {
            $ms['msg'] = '手机号码不正确';
            echo ecm_json_encode($ms);
            return;
        }
        $send_rs = $this->send_mobile_port($method);
        if($send_rs == 1){
            $ms['statu'] = true;
            $ms['msg'] = '验证码已经发送,敬请查看!';
            echo ecm_json_encode($ms);
            return;
        }
        else if($send_rs == -2)
        {
            $ms['msg'] = '发送的次数超过了限制次数!';
            echo ecm_json_encode($ms);
            return;
        }
        else
        {
            $ms['msg'] = '发送失败!';
            echo ecm_json_encode($ms);
            return;
            
        }
    }
    
    /**
     * 检查手机验证码是否正确
     *
     */
    function check_mobile_code()
    {
        if (empty($this->_user_id)) {
            $ret_url = urlencode(get_page_url());
            $this->show_warning("please_login", 'login',
                'index.php?app=member&act=login&ret_url=' . $ret_url);
            return;
        }
        $mode = trim($_GET['mode']);
        $mobile_code = trim($_POST['mobile_verification_code']);                
        if($mode == 'set_pay_password')//以绑定手机方式检查设置支付密码
        {    
            
            $binding_mobile = $this->_user_safety_mod->getOne("SELECT binding_mobile FROM {$this->_user_safety_mod->table} WHERE user_id = {$this->_user_id} ");
            if(!$binding_mobile)
            {
                 $this->show_warning("请先绑定手机再设置",'goback', 'index.php?app=account_security&act=authen_verify&mode=set_mobile&from='.$this->_member_from);
                 return ;
            }
            if(!isset($_SESSION['start_sent_time']) || time() - $_SESSION['start_sent_time'] > 1800)
            {
                $this->show_warning("手机验证码已无效请重新发送!");
                return;
            }
            if ($binding_mobile != $_SESSION['mobile'])
            {
                $this->show_warning("手机号码不正确!");
                return false;
            }
            if($mobile_code != $_SESSION['mobile_code'])
            {
                $this->show_warning("手机验证码错误!");
                return;
            }       
            
            $this->drop_mobile_session();
            $_SESSION['set_pay_password_step'] =  2;
            header("Location:index.php?app=account_security&act=authen_verify&mode=set_pay_password&set_type=mobile&step=2&from=" . $this->_member_from);
            return;
            
        }
        if($mode == 'find_pay_password')//以绑定手机方式检查找回支付密码
        {    
            $binding_mobile = $this->_user_safety_mod->getOne("SELECT binding_mobile FROM {$this->_user_safety_mod->table} WHERE user_id = {$this->_user_id} ");
            if(!$binding_mobile)
            {
                 $this->show_warning("请先绑定手机再设置",'goback', 'index.php?app=account_security&act=authen_verify&mode=set_mobile&from='.$this->_member_from);
                 return ;
            }
            if(!isset($_SESSION['start_sent_time']) || time() - $_SESSION['start_sent_time'] > 1800)
            {
                $this->show_warning("手机验证码已无效请重新发送!");
                return;
            }
            if ($binding_mobile != $_SESSION['mobile'])
            {
                $this->show_warning("手机号码不正确!");
                return false;
            }
            if($mobile_code != $_SESSION['mobile_code'])
            {
                $this->show_warning("手机验证码错误!");
                return;
            }       
            
            $this->drop_mobile_session();
            $_SESSION['find_pay_password_step'] =  2;
            header("Location:index.php?app=account_security&act=authen_verify&mode=find_pay_password&set_type=mobile&step=2&from=" . $this->_member_from);
            return;
            
        }

    }
    
    
    /**
     * 检查手机号码是否正确
     *
     */
    function chack_mobile_name()
    {
        $old_phone_mob = trim($_POST['old_phone_mob']);
        $binding_mobile = $this->_user_safety_mod->getOne("SELECT binding_mobile FROM {$this->_user_safety_mod->table} WHERE user_id = {$this->_user_id} ");
        if($old_phone_mob != $binding_mobile)
        {
            echo ecm_json_encode(false);
            return;
        }
        
        echo ecm_json_encode(true);
    }
    
    /**
     * 检查手机验证码是否正确AJAX方式 
     *
     */
    
    function chack_verification_code()
    {
        $mobile_verification_code = trim($_POST['mobile_verification_code']);
        if ($mobile_verification_code != $_SESSION['mobile_code'] || (!isset($_SESSION['start_sent_time']) || time() - $_SESSION['start_sent_time'] > 1800)) {
            echo ecm_json_encode(false);
            return;
        }
        echo ecm_json_encode(true);
        
    }
    
     /**
     * 通过请求把手机号码记录到$_SESSION['mobile_ready_send_sms']中
     *
     */    
    function set_mobile_session()
    {

        $mobile = trim($_POST['phone_mob']);
        if (empty($mobile) || !is_mobile($mobile)) {       
            echo ecm_json_encode(false);
            return;
        }
        $this->set_mobile_ready($mobile);
        echo ecm_json_encode(true);      
        
    }
    
    /**
     * 把手机号码记录到$_SESSION['mobile_ready_send_sms']中
     *
     */
    function set_mobile_ready($mobile)
    {
        if(isset($_SESSION['mobile_ready_send_sms']))
        {
            unset($_SESSION['mobile_ready_send_sms']);
        }        
        $_SESSION['mobile_ready_send_sms'] = $mobile;
        
        
    }
    
    /**
     * 验证完后把手机号码验证码$_SESSION['mobile_code']与手机$_COOKIE['mobile']删除
     *
     */
    function drop_mobile_session()
    {
        if(isset($_SESSION['mobile_code']))
        {
            unset($_SESSION['mobile_code']);
        }
        if(isset($_SESSION['mobile']))
        {
            unset($_SESSION['mobile']);
        }        
        if(isset($_SESSION['start_sent_time']))
        {
            unset($_SESSION['start_sent_time']);
        }            
        
    }
    
    /**
     * 连接手机接口发送文字短信
     * @param    $method 操作类型 1.binging_mobile绑定手机 2.edit_binging_mobile修改绑定手机 3.pay_password_mobile设置支付密码
     *                            4.pay_password_find_mobile 找回支付密码 5.register_mobile用户注册  6.find_password_mobile找回密码
     * @return int | 1发送成功,-1手机号码不存在,-2发送的次数超过了限制,-3插入数据库失败,-4发送短信失败
     */
    function send_mobile_port($method='')
    {
        $mobile = isset($_SESSION['mobile_ready_send_sms']) ? trim($_SESSION['mobile_ready_send_sms']) : '';

        if (!$mobile)
        {
            return -1;        
        }        
        unset($_SESSION['mobile_ready_send_sms']);
        //$ip = real_ip();
        $ip = $_SERVER["SERVER_ADDR"];
        if (!$this->_mobile_log_mod->validate_rightful($mobile, $ip))
        {
             return -2;  
        }
        if (isset($_SESSION['start_sent_time']) && time() - $_SESSION['start_sent_time'] < 1800 && $_SESSION['mobile_code'])
        {
            $code = $_SESSION['mobile_code'];
        }
         else 
        {
            $code = $this->_rand();
        }
       // $code = $this->_rand();
        if ($this->send_code($mobile, $code, $method))
        {
            $data = array(
                'user_id'      => $this->_user_id,
                'mobile_code'  => $code,
                'mobile'       => $mobile,
                'ip'           => $ip,
                'send_date'    => date('Y-m-d H:i:s'),               
            );
          if (!($this->_mobile_log_mod->add($data)))
          {
            return -3;
          }
          $_SESSION['mobile_code'] = $code;
          $_SESSION['mobile'] = $mobile;
          $_SESSION['start_sent_time'] = time();

          return 1;
        }
        else
        {
          return -4;
        }
    
    }
    
    /**
     * 连接手机接口发送文字短信
     * @param    $method 操作类型 1.binging_mobile绑定手机 2.edit_binging_mobile修改绑定手机 3.pay_password_mobile设置支付密码
     *                            4.pay_password_find_mobile 找回支付密码 5.register_mobile用户注册 6.find_password_mobile找回密码
     * @return int | 1发送成功,-1手机号码不存在,-2发送的次数超过了限制,-3插入数据库失败,-4发送短信失败
     */
    function send_code($mobile, $code, $method='')
    {
        //return true;
       include(ROOT_PATH.'/includes/sendsms/ueswt.php');
       
        $msg = '';    
        switch ($method)
        {
            case 'binging_mobile': //绑定手机
                $msg = '尊敬的客户，您于'.date('m月d日 H:i:s').'设置手机绑定,验证码为:'.$code.'。';
                break;
            case 'edit_binging_mobile': //修改绑定手机
                $msg = '尊敬的客户，您于'.date('m月d日 H:i:s').'修改手机绑定,验证码为:'.$code.'。';
                break;
            case 'pay_password_mobile': //设置支付密码
                $msg = '尊敬的客户，您于'.date('m月d日 H:i:s').'设置支付密码，验证码为:'.$code.'。';
                break;
            case 'pay_password_find_mobile': //找回支付密码
                $msg = '尊敬的客户，您于'.date('m月d日 H:i:s').'找回支付密码，验证码为:'.$code.'。';
                break;
            case 'register_mobile': //用户注册
                $msg = '尊敬的客户，您于'.date('m月d日 H:i:s').'注册万菱家饰网，验证码为:'.$code.'。';
                break;
            case 'find_password_mobile': //找回密码
                $msg = '尊敬的客户，您于'.date('m月d日 H:i:s').'重设密码，验证码为:'.$code.'。';
                break;
            default:
                $msg = '您本次的验证码为:'.$code.'。';
                break;
        }
        $gckj = new ueswt();
        return $gckj->send_sms($msg,$mobile);      
    
    }


    /**
     * 构造6位的随机数字
     *
     * @return string | 生成的数字字符串
     */
    function _rand()
    {
        $word = $this->generate_code();
        return $word;
    }

    function generate_code($len = 6)
    {
        $chars = '0123456789';
        for ($i = 0, $count = strlen($chars); $i < $count; $i++) {
            $arr[$i] = $chars[$i];
        }

        mt_srand((double)microtime() * 1000000);
        shuffle($arr);
        $code = substr(implode('', $arr), 4, $len);
        return $code;
    }
}
?>
